/*
 *  Copyright (C) 2011 Glenn Rune Strandbråten
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * ReviseUI.java
 *
 * Created on 27.apr.2011, 14:27:16
 */

package myrmidia.UI;

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import jcolibri.cbrcore.CBRCase;
import myrmidia.CBR.CBREngine;
import myrmidia.Enums.Races;
import myrmidia.UI.Resources.ComboBoxTableCellRenderer;
import myrmidia.UI.Resources.MultipleResults;
import myrmidia.UI.Resources.UnitModel;
import myrmidia.UI.Resources.WindowCloser;
import myrmidia.Util.CollectionControl;
import myrmidia.Util.CreateObjectFromDB;
import myrmidia.Util.PrintFactory;
import myrmidia.Warhammer.Army;
import myrmidia.Warhammer.ArmyUnit;
import myrmidia.Warhammer.Case;
import myrmidia.Warhammer.Unit;

/**
 * User interface that allows a user to inform to change (manually adapt)
 * the system sugestions.
 * @author Glenn Rune Strandbråten
 * @version 1.0
 */
public class ReviseUI extends javax.swing.JFrame implements MultipleResults{

    private Collection<CBRCase> revise;
    private int displaying;
    private boolean[] approved;

    /** Creates new form ReviseUI */
    public ReviseUI() {
        initComponents();
        setLocationRelativeTo(null);
        addWindowListener(new WindowCloser());
        init();
    }

    /**
     * Creates new form ReviseUI
     * @param cases The collection of cases retrieve and adapted from the CaseBase
     * @param parent The JFrame parent
     */
    public ReviseUI(JFrame parent, Collection<CBRCase> cases) {
        initComponents();
        setLocationRelativeTo(parent);
        this.revise = cases;
        displaying=-1;
        init();
        displayNextResult();     
        addWindowListener(new WindowCloser());
    }

    /**
     * Method which initializes the popup menu and object properties.
     */
    private void init(){
        popupMenu = new javax.swing.JPopupMenu("Edit");
        popupAddRow = new javax.swing.JMenuItem("Add row");
        popupAddRow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addUnitButtonActionPerformed(e);
            }
        });
        popupRemoveRow = new javax.swing.JMenuItem("Remove row");
        popupRemoveRow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                removeUnitButtonActionPerformed(e);
            }
        });
        popupView = new javax.swing.JMenuItem("View equipment/utility");
        popupView.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                viewButtonActionPerformed(e);
            }
        });
        popupMenu.add(popupAddRow);
        popupMenu.add(popupRemoveRow);
        popupMenu.add(popupView);
        if(revise!=null)
            approved = new boolean[revise.size()];
        else
            approved = new boolean[1];
        for(int i=0; i<approved.length; i++){
            approved[i]=false;
        }
    }

    /**
     * Method to aquire the player race of the displayed case
     * @return Races The player race enum
     */
    public Races getPlayerRace(){
       return Races.valueOf(playerTextLabel.getText());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        navigationPane = new javax.swing.JPanel();
        previousCaseButton = new javax.swing.JButton();
        nextCaseButton = new javax.swing.JButton();
        displayCountLabel = new javax.swing.JLabel();
        displayInfoLabel = new javax.swing.JLabel();
        doneButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        printButton = new javax.swing.JButton();
        explanationButton = new javax.swing.JButton();
        caseIDLabel = new javax.swing.JLabel();
        playerLabel = new javax.swing.JLabel();
        opponentLabel = new javax.swing.JLabel();
        pointLabel = new javax.swing.JLabel();
        caseIDTextLabel = new javax.swing.JLabel();
        playerTextLabel = new javax.swing.JLabel();
        opponentTextLabel = new javax.swing.JLabel();
        pointTextLabel = new javax.swing.JLabel();
        unitPanel = new javax.swing.JPanel();
        unitScroll = new javax.swing.JScrollPane();
        unitTable = new javax.swing.JTable();
        addUnitButton = new javax.swing.JButton();
        removeUnitButton = new javax.swing.JButton();
        viewButton = new javax.swing.JButton();
        useCaseCheckBox = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Myrmidia - Revise");

        navigationPane.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        previousCaseButton.setText("<");
        previousCaseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previousCaseButtonActionPerformed(evt);
            }
        });

        nextCaseButton.setText(">");
        nextCaseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextCaseButtonActionPerformed(evt);
            }
        });

        displayCountLabel.setText("1/1");

        displayInfoLabel.setText("Displaying case (army)");

        doneButton.setMnemonic('d');
        doneButton.setText("Done");
        doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                doneButtonActionPerformed(evt);
            }
        });

        cancelButton.setMnemonic('c');
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        printButton.setMnemonic('P');
        printButton.setText("Print");
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout navigationPaneLayout = new javax.swing.GroupLayout(navigationPane);
        navigationPane.setLayout(navigationPaneLayout);
        navigationPaneLayout.setHorizontalGroup(
            navigationPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(navigationPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(previousCaseButton)
                .addGap(18, 18, 18)
                .addComponent(displayInfoLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(displayCountLabel)
                .addGap(17, 17, 17)
                .addComponent(nextCaseButton)
                .addGap(29, 29, 29)
                .addComponent(printButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addComponent(cancelButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(doneButton)
                .addContainerGap())
        );
        navigationPaneLayout.setVerticalGroup(
            navigationPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, navigationPaneLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(navigationPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nextCaseButton)
                    .addComponent(displayInfoLabel)
                    .addComponent(previousCaseButton)
                    .addComponent(displayCountLabel)
                    .addComponent(doneButton)
                    .addComponent(cancelButton)
                    .addComponent(printButton))
                .addContainerGap())
        );

        explanationButton.setMnemonic('e');
        explanationButton.setText("Get explanation");
        explanationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                explanationButtonActionPerformed(evt);
            }
        });

        caseIDLabel.setText("Case id:");

        playerLabel.setText("Player race:");

        opponentLabel.setText("Opponent race:");

        pointLabel.setText("Army points:");
        pointLabel.setToolTipText("Shows the number of used army points over the number of available army points");

        caseIDTextLabel.setText("<placeholder>");

        playerTextLabel.setText("<placeholder>");

        opponentTextLabel.setText("<placeholder>");

        pointTextLabel.setText("<placeholder>");

        unitPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Units"));

        unitTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Unit name", "Number of units"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        unitTable.setRowHeight(20);
        unitTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                unitTableMouseReleased(evt);
            }
        });
        unitScroll.setViewportView(unitTable);

        addUnitButton.setMnemonic('a');
        addUnitButton.setText("Add unit");
        addUnitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addUnitButtonActionPerformed(evt);
            }
        });

        removeUnitButton.setMnemonic('r');
        removeUnitButton.setText("Remove unit");
        removeUnitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeUnitButtonActionPerformed(evt);
            }
        });

        viewButton.setMnemonic('v');
        viewButton.setText("View equipment/utility");
        viewButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout unitPanelLayout = new javax.swing.GroupLayout(unitPanel);
        unitPanel.setLayout(unitPanelLayout);
        unitPanelLayout.setHorizontalGroup(
            unitPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, unitPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(unitScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 319, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(unitPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(viewButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(removeUnitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(addUnitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        unitPanelLayout.setVerticalGroup(
            unitPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(unitPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(unitPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(unitScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
                    .addGroup(unitPanelLayout.createSequentialGroup()
                        .addComponent(addUnitButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeUnitButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(viewButton)))
                .addContainerGap())
        );

        useCaseCheckBox.setMnemonic('u');
        useCaseCheckBox.setText("Use case (army)");
        useCaseCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                useCaseCheckBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(navigationPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(opponentLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(opponentTextLabel)
                .addContainerGap(351, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(caseIDLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(caseIDTextLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(playerLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(playerTextLabel)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 250, Short.MAX_VALUE)
                .addComponent(explanationButton)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(pointLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pointTextLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 253, Short.MAX_VALUE)
                        .addComponent(useCaseCheckBox))
                    .addComponent(unitPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(navigationPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(caseIDLabel)
                            .addComponent(caseIDTextLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(playerLabel)
                            .addComponent(playerTextLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(opponentLabel)
                            .addComponent(opponentTextLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(pointLabel)
                            .addComponent(pointTextLabel)
                            .addComponent(useCaseCheckBox)))
                    .addComponent(explanationButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(unitPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Action performed when the previousCaseButton is selected
     * @param evt The ActionEvent trigger
     */
    private void previousCaseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousCaseButtonActionPerformed
        displayPreviousResult();
}//GEN-LAST:event_previousCaseButtonActionPerformed

    /**
     * Action performed when the nextCaseButton is selected
     * @param evt The ActionEvent trigger
     */
    private void nextCaseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextCaseButtonActionPerformed
        displayNextResult();
}//GEN-LAST:event_nextCaseButtonActionPerformed

    /**
     * Action performed when the nextButton is selected
     * @param evt The ActionEvent trigger
     */
    private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doneButtonActionPerformed
        if(verifyRequirements()){
            try{
                setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                Collection<CBRCase> approvedCollection = new HashSet<CBRCase>();
                //Need to change the data representation to the format recognized
                //by the save functionality.
                for(int i=0; i<approved.length; i++){
                    if(approved[i]){
                        CBRCase add=(CBRCase)CollectionControl.getItemAt(revise, i);
                        approvedCollection.add(add);
                    }
                }
                CBREngine.getInstance().retain(approvedCollection);
            }
            finally{
                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                new SelectTaskUI(this).setVisible(true);
                dispose();
            }
        }
        else{
            JOptionPane.showMessageDialog(this,"No cases (armies) are approved, at least one\ncase (army) have to be approved to continue", "Error 05 - No approved cases (armies)", JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_doneButtonActionPerformed

    /**
     * Action performed when the cancelButton is selected
     * @param evt The ActionEvent trigger
     */
    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        new SelectTaskUI(this).setVisible(true);
        dispose();
}//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * Action performed when the explanationButton is selected
     * @param evt The ActionEvent trigger
     */
    private void explanationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_explanationButtonActionPerformed
        new ExplanationUI(this, displaying, ExplanationUI.MODE_JUSTIFICATION).setVisible(true);
    }//GEN-LAST:event_explanationButtonActionPerformed

    /**
     * Action peformed when the addUnitButton is selected
     * @param evt The ActionEvent trigger
     */
    private void addUnitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addUnitButtonActionPerformed
        DefaultTableModel dtm = (DefaultTableModel) unitTable.getModel();
        dtm.addRow(new Object[]{"N/A",null});
    }//GEN-LAST:event_addUnitButtonActionPerformed

    /**
     * The action performed when the removeUnitButton is selected
     * @param evt The ActionEvent trigger
     */
    private void removeUnitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeUnitButtonActionPerformed
        int selectedRow = unitTable.getSelectedRow();
        if(selectedRow==-1)
            return;
        DefaultTableModel dtm = (DefaultTableModel) unitTable.getModel();
        dtm.removeRow(selectedRow);
    }//GEN-LAST:event_removeUnitButtonActionPerformed

    /**
     * Action performed when the viewButton is selected
     * @param evt The ActionEvent trigger
     */
    private void viewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewButtonActionPerformed
        int selectedRow = unitTable.getSelectedRow();
        if(selectedRow==-1)
            return;
        try{
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            int row = unitTable.getSelectedRow();
            CBRCase cbr = (CBRCase)CollectionControl.getItemAt(revise, displaying);
            Case _case = (Case) cbr.getSolution();
            ArmyUnit au = (ArmyUnit)CollectionControl.getItemAt(_case.getArmy().getArmyUnits(), row);
            new EquipmentUtilUI(this, UnitModel.parseUnitModelFromArmyUnitForRevise(au),false).setVisible(true);
        }
        catch(NullPointerException npe){}
        finally{
            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    }//GEN-LAST:event_viewButtonActionPerformed

    /**
     * Action performed when a mouse button is released inside the unitTable
     * @param evt The MouseEvent trigger
     */
    private void unitTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_unitTableMouseReleased
        if(evt.isPopupTrigger()){
            int row = unitTable.rowAtPoint(evt.getPoint());
            unitTable.setRowSelectionInterval(row, row);
            popupMenu.show(unitTable, evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_unitTableMouseReleased

    /**
     * Action performed when the useCaseCheckBox is selected
     * @param evt The ActionEvent trigger
     */
    private void useCaseCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useCaseCheckBoxActionPerformed
        if(useCaseCheckBox.isSelected())
            approved[displaying] = true;
        else
            approved[displaying] = false;
    }//GEN-LAST:event_useCaseCheckBoxActionPerformed

    /**
     * Action performed when the printBtton is selected
     * @param evt The ActionEvent trigger
     */
    private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printButtonActionPerformed
        new PrintUI(revise, this,displaying,true).setVisible(true);
    }//GEN-LAST:event_printButtonActionPerformed
    
    public final void displayPreviousResult() {
        displaying = (displaying==0) ? revise.size()-1 : displaying-1;
        displayResult();
    }

    public final void displayNextResult() {
        displaying = (displaying==revise.size()-1) ? 0 : displaying+1;
        displayResult();
    }

    public void displayResult(){
        System.out.println("DISPLAYING: "+displaying);
        CBRCase cbrCase=(CBRCase)CollectionControl.getItemAt(revise, displaying);
        Case _case = (Case) cbrCase.getSolution();
        caseIDTextLabel.setText(""+_case.getID());
        playerTextLabel.setText(_case.getArmy().getPlayerRace().toString());
        opponentTextLabel.setText(_case.getOpponent().toString());
        pointTextLabel.setText(_case.getArmy().calculateCost()+"/"+
            _case.getArmy().getArmyPoints());
        displayCountLabel.setText((displaying+1)+"/"+revise.size());
        populateUnitsTable();
        if(approved[displaying])
            useCaseCheckBox.setSelected(true);
        else
            useCaseCheckBox.setSelected(false);
    }

    public void populateUnitsTable(){
        DefaultTableModel dtm = (DefaultTableModel) unitTable.getModel();
        int rows = unitTable.getRowCount();
        for(int i=rows-1; i>-1; i--)
            dtm.removeRow(i);
        CBRCase cbrCase=(CBRCase)CollectionControl.getItemAt(revise,displaying);
        Case _case = (Case) cbrCase.getSolution();
        PrintFactory.printCase(_case, false, null);                
        Army army = _case.getArmy();
        populateUnitComboBox(army.getPlayerRace());
        for(ArmyUnit unit : army.getArmyUnits()){
            String name = unit.getUnit().getName().split(":")[1];
            int num = unit.getNumberOfUnits();
            dtm.addRow(new Object[]{name,num});
        }
    }

    /**
     * Method to populate the unit drop down menu in the first column in unitTable
     * @param race The Race of the units to populate the drop down list with
     */
    public void populateUnitComboBox(Races race){
        List<Unit> unit = CreateObjectFromDB.getRaceUnits(race);
        String[] names = new String[unit.size()+1];
        names[0] = "N/A";
        int pos = 1;
        for (Unit u : unit) {
            String name = u.getName();
            String[] array = name.split(":");
            names[pos++] = array[1];
        }
        unitTable.getColumnModel().getColumn(0).setCellRenderer(new ComboBoxTableCellRenderer(names, 0));
    }

    /**
     * Method to verify if the requirements to continue is met.
     * @return true if at least one case is approved, false if no cases are
     * approved
     */
    public boolean verifyRequirements(){
        for (boolean b : approved) {
            if(b)
                return true;
        }
        return false;
    }
    
    public void parseUnitModelForSelectedUnit(UnitModel model){
        CBRCase cbr = (CBRCase)CollectionControl.getItemAt(revise, displaying);
        Case _case = (Case) cbr.getSolution();
        ArmyUnit armyUnit = (ArmyUnit) CollectionControl.getItemAt(_case.getArmy().getArmyUnits(), unitTable.getSelectedRow());
        armyUnit.parseUnitModel(model);
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ReviseUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addUnitButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel caseIDLabel;
    private javax.swing.JLabel caseIDTextLabel;
    private javax.swing.JLabel displayCountLabel;
    private javax.swing.JLabel displayInfoLabel;
    private javax.swing.JButton doneButton;
    private javax.swing.JButton explanationButton;
    private javax.swing.JPanel navigationPane;
    private javax.swing.JButton nextCaseButton;
    private javax.swing.JLabel opponentLabel;
    private javax.swing.JLabel opponentTextLabel;
    private javax.swing.JLabel playerLabel;
    private javax.swing.JLabel playerTextLabel;
    private javax.swing.JLabel pointLabel;
    private javax.swing.JLabel pointTextLabel;
    private javax.swing.JButton previousCaseButton;
    private javax.swing.JButton printButton;
    private javax.swing.JButton removeUnitButton;
    private javax.swing.JPanel unitPanel;
    private javax.swing.JScrollPane unitScroll;
    private javax.swing.JTable unitTable;
    private javax.swing.JCheckBox useCaseCheckBox;
    private javax.swing.JButton viewButton;
    // End of variables declaration//GEN-END:variables
    private javax.swing.JMenuItem popupRemoveRow;
    private javax.swing.JMenuItem popupAddRow;
    private javax.swing.JMenuItem popupView;
    private javax.swing.JPopupMenu popupMenu;
}